# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""User Model"""

import datetime
from zoom import zoomer
import dzentity, dzmodel

class User(dzmodel.Record):
    def clear(self):
            self.LOGINID = self.FIRSTNAME = self.LASTNAME = self.EMAIL = self.PHONE = self.FAX = ''
            self.STATUS  = 'A'
            self.DTADD = self.DTUPD = datetime.datetime.now()

    def get_FULLNAME(self):
        return self.FIRSTNAME + (self.FIRSTNAME and self.LASTNAME and ' ') + self.LASTNAME

    def authenticate(self,password):
        real_password = zoomer.db("select OLD_PASSWORD('%s')" % password)[0][0]
        return real_password == self.PASSWORD

    def set_password(self,password):
        old = self.PASSWORD
        new = zoomer.db("select OLD_PASSWORD('%s')" % password)[0][0]
        self.PASSWORD = new


class Users(dzmodel.Table):
    def __init__(self):
        dzmodel.table_prefix = 'dz_'
        dzmodel.Table.__init__(self,User)
        self.table_key = 'USERID'

    def current(self):
        #userid = zoomer.session.userid or 2
        userid = zoomer.user_id or 2
        return self.seek(userid)

    def find_by_loginid(self,loginid):
        rec = zoomer.db('select userid from dz_users where loginid=%s',loginid)
        if rec:
            return self.seek(rec[0].USERID)

    def find_by_email(self,loginid):
        rec = zoomer.db('select userid from dz_users where email=%s',loginid)
        if rec:
            return self.seek(rec[0].USERID)

if __name__ == '__main__':
    import unittest

    class TestUser(unittest.TestCase):
        def test_instantiate(self):
            users = Users()
            self.assert_(users)

        def test_get_user(self):
            users = Users()
            user = users.seek(1)
            self.assertEqual(user.USERID,1)
            self.assertEqual(user.LASTNAME,'User')

        def test_get_current_user(self):
            zoomer.user_id = 2
            users = Users()
            user = users.current()
            self.assertEqual(user.USERID,2)
            self.assertEqual(user.LASTNAME,'Known')

        def test_find_user(self):
            users = Users()
            self.assertEqual(users.find_by_loginid('guest').USERID,3)

        def test_not_find_user(self):
            users = Users()
            self.assertEqual(users.find_by_loginid('guesst'),None)

    unittest.main()




# class Profile(dzmodel.Entity):
#     def __init__(self,rec=None):
#         """Initialize a new entity"""
#         #dzmodel.Entity.__init__(self,rec)
#         self.__rec = self._from_rec(rec)
#         self.table_name = 'dz_users'
#         self.users_table = Users()
#
#     def _from_rec(self,rec):
#         if type(rec) == DictType:
#             if 'key' in rec.keys(): self.__dict__['USERID'] = rec['key']
#             for name in rec:
#                 self.__dict__[name.lower()] = rec[name]
#         return rec
#
#     def seek(self, userid):
#         """Return the record for userid or None if not found"""
#         #data = zoomer.db.query("select * from %s where userid=%d;",(self.table_name,userid))
#         data = zoomer.db.query("select * from %s where userid=%d;"%(self.table_name,userid))
#         return (len(data)==1 and data[0] or None)
#
#     def is_user(self, userid):
#         """Is the supplied userid valid"""
#         return self.find(userid)
#
#     def is_loginid(self, loginid):
#         """Is the supplied loginid valid"""
#         data = zoomer.db.query("select * from %s where loginid='%s';"%(self.table_name,loginid))
#         return (len(data)==1 and data[0] or None)
#
#     def find(self, userid):
#         """Does the userid exist"""
#         return self.seek(userid) and 1 or 0
#
#     def update(self,rec):
#         """Update a users profile record"""
#         self.users_table.update(rec)
#
#     def new(self,rec):
#         """Create a new record for the profile provided"""
#         return self.users_table.new(rec)
#
#     def get_time_since_last_update(self):
#         """Get the time since the last update"""
#         if self.dateupd==None: return None
#         delta = datetime.today() - self.dateupd
#         days = delta.days
#         return round(delta.days+(float(delta.seconds)/float(86400)),1)
#
# class Users(dzmodel.Table):
#     def __init__(self):
#         """Users table initialization"""
#         self.table_prefix = 'dz_'
#         dzmodel.Table.__init__(self,Profile)
#         self.columns = zoomer.db('select * from %s where 1=0' % (self.table_name)).columns
# 
#     def update(self,rec):
#         """Update the users record"""
#         field_values = dict(zip(self.field_names,[getattr(rec,field_name.lower()) for field_name in self.field_names]))
#         # only update fields in the profile record
#         #   doing it the same wa y as Table would let us 'blank' a field
#         field_names = [key for key in field_values if key in rec._Profile__rec.keys()]
# 
#         fields = ','.join(field_names)
#         params = ','.join(['%s=%s' % (k,'%s') for k in field_names])
#         values = [field_values[key] for key in field_names]
#         cmd = 'update %s set %s, dtupd=now() where userid=%s' % (self.table_name,params,rec.userid)
#         zoomer.db(cmd,*values)
# 
#     def new(self,rec):
#         """Add the new record for the users/contacts table"""
#         return zoomer.acl.add_contact(zoomer.session.loginid,'',rec.FIRSTNAME or '',
#                 rec.LASTNAME or '',rec.EMAIL or '',rec.PHONE or '',rec.FAX or '')